package com.huang.readwriteLock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/*
        可重入读写锁：

*               持有写锁  可以在获取读锁  （意思：将写锁降级为读锁）√
*               持有读锁   不可以再去获取写锁  需要先释放读锁(悲观锁理念：读的时候不能写)


*
*
*       读锁全完  写锁有望
*       写锁独占   读写全堵
*
*           锁降级原因：
                    1 保证 写锁 的数据 可以被读 数据可可见性
                    2 不希望 独占锁 占太多时间非常耗时   降级为读锁
*
* */
public class readWriteLockDemo {
  static   int num=0;
    public static void main(String[] args) throws InterruptedException {
        ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();
        ReentrantReadWriteLock.WriteLock writeLock = reentrantReadWriteLock.writeLock();
        ReentrantReadWriteLock.ReadLock readLock = reentrantReadWriteLock.readLock();
        for (int j = 0;j < 3; j++) {
            new    Thread(()->{
                try {
                    writeLock.lock();
                    for (int i = 0; i < 100; i++) {
                        num++;
                    }
                    readLock.lock();
                } finally {
                    writeLock.unlock();
                }
                System.out.println(num);
                readLock.unlock();

            }).start();
        }
        }







}


